import poser, os, sys, math

os.chdir( os.path.dirname(poser.AppLocation()) )

sys.path.append( os.path.join("Runtime","Python","PoseWorks","GlowWorm","Data"))

import gwoClip

def getDistFromCam(actor, camera):
	pCx, pCy, pCz = camera.LocalDisplacement()
	pAx, pAy, pAz = actor.WorldDisplacement()
	pOx, pOy, pOz = actor.Origin()
	d = (pCx - pAx - pOx)**2 + (pCy - pAy - pOx)**2 + (pCz - pAz - pOz)**2
	d = math.sqrt(d)
	return d

def getCamera():
	return poser.Scene().CurrentCamera()

def getDofProp():
	try:
		return poser.Scene().ActorByInternalName("GWO_DOF_1")
	except:
		return None

def getFocusDistParm(camera):
	return camera.ParameterByCode( poser.kParmCodeFOCUSDISTANCE )

def setDof( parm=None, v=0 ):
	camera = getCamera()
	dof = getDofProp()
	if dof:
		camFocusDist = getFocusDistParm(camera)
		d = getDistFromCam( dof, camera )
		camFocusDist.SetValue( d )

def addGwoDof():
	if getDofProp():
		setDof()
		return None
	else:
		gwoDofPath = os.path.join("Runtime","Python","PoseWorks","GlowWorm","Data","gwoDof.pp2")
		return gwoClip.addGwoProp( gwoDofPath )

if __name__ == '__main__':
	camera = getCamera()
	dof = getDofProp()
	if dof:
		#for parmCode in [ poser.kParmCodeXTRAN, poser.kParmCodeYTRAN, poser.kParmCodeZTRAN ]:
		#	dof.ParameterByCode( parmCode ).SetUpdateCallback( setDof )
		#for parmCode in [ poser.kParmCodeXTRAN, poser.kParmCodeYTRAN, poser.kParmCodeZTRAN, poser.kParmCodeXROT, poser.kParmCodeYROT, poser.kParmCodeZROT ]:
		#	camera.ParameterByCode( parmCode ).SetUpdateCallback( setDof )
		setDof()
pass
